package com.ft.data.rabbitmq;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @copyright (C), 2015-2019, XXX有限公司
 * @fileName: RabbitConfig
 * @author: FT-Lee
 * @date: 2019/5/5 11:12
 * @description: rabbitmq配置
 * @history: <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
@Slf4j
@Configuration
public class RabbitConfig {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 主机地址
     */
    @Value("${spring.rabbitmq.host}")
    private String host;

    /**
     * 端口号
     */
    @Value("${spring.rabbitmq.port}")
    private int port;

    /**
     * 用户名
     */
    @Value("${spring.rabbitmq.username}")
    private String username;

    /**
     * 连接密码
     */
    @Value("${spring.rabbitmq.password}")
    private String password;

    /**
     * 虚拟机名称
     */
    @Value("${spring.rabbitmq.virtualHost}")
    private String virtualHost;

    /**
     * 是否启用,默认false
     */
    @Value("${spring.rabbitmq.enabled:false}")
    private Boolean enabled;

    @Bean
    @ConditionalOnExpression("${enabled}.equals('true')")
    public ConnectionFactory connectionFactory() {
        logger.info("连接rabbitmq");
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host,port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualHost);
        connectionFactory.setPublisherConfirms(true);
        return connectionFactory;
    }

    /**
     * 必须是prototype类型
     * @return
     */
    @Bean
    @ConditionalOnExpression("${enabled}.equals('true')")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RabbitTemplate rabbitTemplate() {
        return new RabbitTemplate(connectionFactory());
    }
}
